package com.dc.free.util;

import java.time.Duration;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.dialect.Dialect;
import com.jfinal.plugin.druid.DruidPlugin;

public class DruidPluginUtil {
	private static Prop p = PropKit.use("free.properties");
	private static String jdbcType = p.get("jdbc.type");
	private static String dialectClass = p.get(String.format("jdbc.%s.dialect.class", jdbcType));
	
	/**
	 * 插件初始化
	 * @return
	 */
	public static DruidPlugin create(String jdbcType) {
		String jdbcUrl = p.get(String.format("jdbc.%s.url", jdbcType));
		String jdbcUser = p.get(String.format("jdbc.%s.user", jdbcType));
		String jdbcPassword = p.get(String.format("jdbc.%s.password", jdbcType));
		String driverClass = p.get(String.format("jdbc.%s.driver.class", jdbcType));
		
		if("sqlite".equalsIgnoreCase(jdbcType)){
			jdbcUrl = String.format(jdbcUrl, PathKit.getWebRootPath());
		}
		
		//   context/druid/index.html
		StatFilter statFilter = new StatFilter();
		statFilter.setMergeSql(true);
		statFilter.setLogSlowSql(true);
		// 慢查询目前设置为1s,随着优化一步步进行慢慢更改
		statFilter.setSlowSqlMillis(Duration.ofMillis(1000).toMillis());
		
		WallFilter wall = new WallFilter();  
        wall.setDbType(jdbcType);  
        WallConfig config = new WallConfig();  
        config.setFunctionCheck(false); // 支持数据库函数  
        wall.setConfig(config); 
		
		return new DruidPlugin(jdbcUrl, jdbcUser, jdbcPassword)
				   .setDriverClass(driverClass)
				   .addFilter(statFilter)
				   .addFilter(wall);
	}
	
	public static DruidPlugin create() {
		return create(jdbcType);
	}
	
	/**
	 * 获取方言
	 * @return
	 */
	public static Dialect getDialect(String jdbcType) {
		Dialect dialect = null;
		try {
			dialect = (Dialect) Class.forName(p.get(String.format("jdbc.%s.dialect.class", jdbcType))).newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dialect;
	}
	
	public static Dialect getDialect() {
		return getDialect(jdbcType);
	}
}
